<template>
  <div class="article-list">
    <van-pull-refresh
      :success-text="refreshSuccessText"
      success-duration="2000"
      v-model="isRefreshLoading"
      @refresh="onRefresh"
    >
      <!-- van-list -->
      <van-list
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
        <ArticleItem v-for="(item, index) in list" :key="index" :article="item"></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem,
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      // 上拉加载用的
      loading: false,
      finished: false,
      timestamp: undefined,
      error: false,
      // 下拉刷新用的   => 控制文字的显示 和 动画效果
      isRefreshLoading: false,
      refreshSuccessText: '',
    }
  },
  created() {
    console.log('article-list')
  },
  methods: {
    // 下拉刷新
    async onRefresh() {
      //0. 自动改 isRefreshLoading = true

      try {
        //1. 请求数据
        let res = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(), // 下拉获取的是最新的数据 所以用的都是当前最新的时间戳
          with_top: 1,
        })
        let { results } = res.data.data
        //2. 拼接数据
        this.list = [...results, ...this.list]
        // this.list = results

        // 修改提示文字
        this.refreshSuccessText = `刷新成功，更新了${results.length} 条数据`
        //3. 手动改 isRefreshLoading = false 代表本次刷新数据完成
        this.isRefreshLoading = false
      } catch (error) {
        // console.log('可能会出错', error)
        console.dir(error)
      }
    },

    // 上拉加载更多
    async onLoad() {
      //0. 自动改 loading = true

      try {
        //1. 请求数据
        let res = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(), // 时间戳来来获取分页情况的
          with_top: 1,
        })
        // console.log('推荐列表数据', res.data.data)
        let { results, pre_timestamp } = res.data.data
        //2. 拼接数据
        this.list = [...this.list, ...results]

        //3. 手动改 loading = false 代表本次数据 加载完成
        this.loading = false

        //4. 看数据是否还有值
        if (results.length) {
          this.timestamp = pre_timestamp
        } else {
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        this.error = true
        this.$toast.fail('获取失败')
      }
    },
  },
}
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow: auto;
}
</style>
